import pexpect

PROMPT=['# ', '>>> ', '> ', '\$ ', ':~']

def send_command(child, cmd):
	child.sendline(cmd)
	child.expect(PROMPT)
	print(bytes.decode(child.before))

def connect(user, host, password, port = 22):
	ssh_newkey = 'Are you sure you want to continue connecting'
	connStr = 'ssh '
	if port != "22":
		connStr += "-p " + port + " "
	connStr += user + '@' + host
	child = pexpect.spawn(connStr)
	print("Connecting to  ", connStr)
	ret = child.expect([pexpect.TIMEOUT, ssh_newkey, '[P|p]assword:'])
	print("Debug: expect result ", ret)

	if ret == 0:
		print('[-] Error Connecting')
		return
	if ret == 1:
		child.sendline('yes')
		ret = child.expect([pexpect.TIMEOUT, \
			'[P|p]assword:'])
		if ret == 0:
			print('[-] Error Connecting')
			return

		child.sendline(password)
		child.expect(PROMPT)
		return child
	if ret == 2:
		child.sendline(password)
		child.expect(PROMPT)
		return child

def usage():
	print('''This is interactive command line for operation connected linux
	exit - exit this connect
	help - this message
	Other command just what you want to send to linux
	Other special key not support (ctrl+?, up down ...)
	''')

def readconf(file):
	fh = open(file)
	keys = []
	for line in fh.readlines():
		s = line.split(" ")
		onekey = {}
		onekey["addr"] = s[0]
		onekey["port"] = s[1]
		onekey["user"] = s[2]
		onekey["password"] = s[3]
		keys.append(onekey)
	return keys

def print_conf(keys):
	i = 1
	for key in keys:
		print("%d %s %s %s" % (i, key["addr"], key["port"], key["user"]))
		i += 1
	print("")

def main():
	defautconf = "conf/base.conf"
	keys = readconf(defautconf)
	print_conf(keys)
	i = input("Which to connect: ")
	index = int(i)
	index -= 1
	user = keys[index]["user"]
	host = keys[index]["addr"]
	password = keys[index]["password"]
	port = keys[index]["port"]
	try:
		child = connect(user, host, password, port)
	except e:
		print('connect failed ' + e)
		return
	if child == None:
		print("connect failed")
		return
	bexit = False
	while not bexit:
		cmd = input(">> ")
		if cmd == "exit":
			bexit = True
			continue
		if cmd == "help":
			usage()
			continue
		if cmd == "":
			continue
		send_command(child, cmd)

if __name__ == '__main__':
	main()
